new Vue({
    el: '#app',
    data() {
        return {
            colors: colors,
            importJson: '',
            currentBeginDate: option.xAxis.min,
            myOption: option,
            mySpeedOption: speedOption,
            uiTransparent: 230,
            infoDisplay: 0,
            speed: 0,
            addFrom: {
                dateTime: '',
                yuanshi: '',
            },
            marketForm: {
                roleName: '',
                roleDate: '',
                y: 0
            },
            mouthPro: 0,
            maxValue: 1600,
            addDialogVisible: false,
            editDialogVisible: false,
            drawerDialogVisible: false,
            showOutJsonDialog: false,
            showInJsonDialog: false,
            addMarkerDialog: false,
            showInfoDialog: false,
            rules: {
                dateTime: [
                    {required: true, message: '请选择日期', trigger: 'blur'},
                ],
                yuanshi: [
                    {required: true, message: '请告诉我你的原石', trigger: 'blur'},
                ],
                roleName: [
                    {required: true, message: '请输入五星名字', trigger: 'blur'},
                ],
                roleDate: [
                    {required: true, message: '请选择出货日期', trigger: 'blur'},
                ],
            }
        }
    },
    watch: {
        currentBeginDate(val, old) {
            setTimeout(() => {
                this.$set(this.myOption.xAxis, 'min', val);
                this.myChart.setOption(this.myOption, true);
            }, 250)
        },
        speed(val, old){
            this.mySpeedOption.series[0].data[0].value = val;
            this.speedChart.setOption(this.mySpeedOption, true);
        },
    },
    mounted() {
        this.loadSetting();
        this.init();
        window.addEventListener("resize", ()=> {
            this.myChart.resize();
            this.speedChart.resize();
        });
    },
    computed: {
        currentYuanshi(){
            let t = this.myOption.series[0].data;
            if (t) {
                return t[t.length - 1][1]
            }
            return 0;
        }
    },
    methods: {
        loadSetting(){
            let uiTransparent = localStorage.getItem(UI_TRANS);
            let maxValue = localStorage.getItem(MAX_VALUE);
            let currentBeginDate = localStorage.getItem(BEGIN_DATE);
            this.$set(this, 'uiTransparent', uiTransparent ? parseInt(uiTransparent) : 230);
            this.$set(this, 'maxValue', maxValue ? parseInt(maxValue) : 28800);
            this.$set(this, 'currentBeginDate', currentBeginDate ? currentBeginDate : '2020-09-15');
        },
        resetSetting(){
            this.$confirm(`将重置显示配置?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$set(this, 'uiTransparent', 230);
                this.$set(this, 'maxValue', 28800);
                this.$set(this, 'currentBeginDate', '2020-09-15');
                this.saveSetting();
                this.init();
            });
        },
        saveSetting(){
            try {
                localStorage.setItem(UI_TRANS, this.uiTransparent);
                localStorage.setItem(MAX_VALUE, this.maxValue);
                localStorage.setItem(BEGIN_DATE, this.currentBeginDate);
                this.$message.success("保存配置成功");
            } catch(e) {
                this.$message.error("保存配置失败");
            }
        },
        //更改图表最大值显示
        changeMax(){
            //计算最大值
            this.$set(this.myOption.yAxis, "max", this.maxValue);
            this.myChart.setOption(this.myOption, true);
        },
        //保存编辑数据
        saveEditData(){
            if (!this.myOption.series[0].data){
                this.$message.error("数据异常")
                return;
            }
            let flag = false;
            this.myOption.series[0].data.forEach(item => {
                if (!item || !item[0] || item[1] < 0){
                    flag = true;
                }
            });
            if (flag){
                this.$message.warning("数据未填写完整")
                return;
            }
            this.writeLocalData(this.myOption.series[0].data);
            this.$message.success("保存成功, 正在等待刷新页面");
            this.editDialogVisible = false;
            setTimeout(() => {
                this.init();
            }, 1000)
        },
        deleteData(index){
            this.$confirm(`将清除这一条${this.myOption.series[0].data[index][0]}
                ,原石为${this.myOption.series[0].data[index][1]}的数据?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.myOption.series[0].data.splice(index, 1);
            });
        },
        showEditDialog(){
            this.editDialogVisible = true;
        },
        //导入数据
        importData(){
            try {
                if (this.importJson.length < 10) {
                    this.$message.error("请把复制的json粘贴到这里重试")
                    return;
                }
                localStorage.setItem(CACHE_NAME, JSON.stringify(JSON.parse(this.importJson)));
                this.$message.success("导入成功");
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } catch (e) {
                this.$message.error("JSON格式错误")
            }
        },
        //初始化图表
        async init(){
            this.myChart = echarts.init(document.getElementById('mainChart'));
            this.speedChart = echarts.init(document.getElementById('speedChart'));
            //替换本地数据
            let data = await this.loadLocalData();
            this.$set(this.myOption.series[0], "data", data.date);
            this.$set(this.myOption.series[0].markPoint, "data", data.marker);
            //计算最大值
            this.$set(this.myOption.yAxis, "max", this.maxValue);
            //更新时间显示区间
            this.$set(this.myOption.xAxis, 'max', this.pushHalfYear(140));
            this.$set(this.myOption.xAxis, 'min', this.currentBeginDate);
            //计算预测值
            let forecast = this.computeForecast();
            if (forecast) {
                this.$set(this.myOption.series[1], 'data', forecast);
            }
            //最后一点闪烁
            this.myOption.series[2].data[0] = this.myOption.series[0].data[this.myOption.series[0].data.length-1];
            this.myChart.setOption(this.myOption, true);
            this.speedChart.setOption(speedOption);
            //计算到达大保底的百分比
            try{
                this.mouthPro = (this.myOption.series[2].data[0][1] / 160 / 160 * 100).toFixed(1);
            } catch (e){
                this.mouthPro = 0;
            }
        },
        //获取本地缓存数据
        async loadLocalData() {
            let sdata = localStorage.getItem(CACHE_NAME);
            let data = JSON.parse(sdata);
            let temp = {
                date: data ? data.date : [],
                marker: data ? data.marker : [],
            }
            console.info(temp)
            return temp;
        },
        computeMaxValue() {
            let resData = this.myOption.series[0].data;
            let max = 0;
            resData.forEach((item => {
                if (item[1] && parseInt(item[1]) > max) {
                    max = parseInt(item[1]);
                }
            }));
            if (max < 14400) {
                this.maxValue = 14400;
            } else{
                this.maxValue = 14400 * (parseInt(max / 14400) + 1);
            }
            return this.maxValue;
        },
        writeLocalData(tempData = []) {
            let sdata = localStorage.getItem(CACHE_NAME);
            let data = JSON.parse(sdata);
            if (!data) {
                data = {
                    date: [],
                    marker: []
                }
            }
            data.date = tempData;
            localStorage.setItem(CACHE_NAME, JSON.stringify(data));
            this.$message.success("添加成功")
        },
        showAddDialog() {
            this.addDialogVisible = true;
            this.addFrom = {
                dateTime: '',
                yuanshi: 0,
            }
        },
        //保存原石记录
        saveYuanshi() {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    let {dateTime, yuanshi} = this.addFrom;
                    let tempData = this.myOption.series[0].data;
                    //插入新记录
                    tempData.push([dateTime, yuanshi]);
                    //重新按日期排序,防止图表错乱
                    tempData.sort((current, next) => {
                        var oDate1 = new Date(current[0]);
                        var oDate2 = new Date(next[0]);
                        return oDate1.getTime() - oDate2.getTime();
                    })
                    //更新本地缓存
                    this.writeLocalData(tempData);
                    //更新本地
                    //this.$set(this.myOption.series[0], "data", tempData);
                    this.init();
                    this.addDialogVisible = false;
                    this.drawerDialogVisible = false;
                }
            });
        },
        cleanAll(){
            this.$confirm('将清除所有数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                localStorage.clear();
                this.$message.success("清除成功");
                setTimeout(() => {
                    location.reload();
                }, 1000)
            })
        },
        showAddMarkerDialog() {
            this.addMarkerDialog = true;
        },
        AddMarket(){
            this.$refs.marketForm.validate((valid) => {
                if (valid) {
                    let tempData = this.myOption.series[0].markPoint.data;
                    tempData.push({
                        name: this.marketForm.roleName,
                        xAxis: this.marketForm.roleDate,
                        yAxis: this.marketForm.y
                    });
                    let sdata = localStorage.getItem(CACHE_NAME);
                    let data = JSON.parse(sdata);
                    if (!data) {
                        data = {
                            date: [],
                            marker: []
                        }
                    }
                    data.marker = tempData;
                    localStorage.setItem(CACHE_NAME, JSON.stringify(data));
                    this.$message.success("添加成功");
                    this.addMarkerDialog = false;
                    this.drawerDialogVisible = false;
                    this.init();
                }
            });
        },
        //计算出最后一点推后半年后的日期
        pushHalfYear(day = 0){
            let dateobj;
            if (this.myOption.series[0].data.length > 0) {
                let tempData = this.myOption.series[0].data;
                dateobj = new Date(tempData[tempData.length-1][0]);
            } else{
                dateobj = new Date();
            }
            dateobj.setDate(dateobj.getDate() + day);
            let push90DateStr = `${dateobj.getFullYear()}-${(dateobj.getMonth()+1).toString().padStart(0,2)}-${(dateobj.getDate()).toString().padStart(0,2)}`;
            return push90DateStr;
        },
        //预测趋势线
        computeForecast() {
            //数据大于5个点才计算
            let point = 6;
            if (this.myOption.series[0].data.length >= point) {
                // 计算最近6个点中的最大值,
                let recent = this.myOption.series[0].data.slice(-point);
                let maxItem = [0,0];
                let minItem = [0,999999];
                let maxIndex = -1;
                let minIndex = -1;
                //找最大值
                recent.forEach((item, index) => {
                    if (maxItem[1] < parseInt(item[1])){
                        maxItem = item;
                        maxIndex = index;
                    }
                });
                //如果最大值在第一个点, 则删除最大值重新找一次最大值
                if (maxIndex == 0){
                    recent.splice(0, 1);
                    maxItem = [0,0];
                    maxIndex = -1;
                    recent.forEach((item, index) => {
                        if (maxItem[1] < parseInt(item[1])){
                            maxItem = item;
                            maxIndex = index;
                        }
                    });
                }
                //--------------------------------------
                //找最小值
                recent.forEach((item, index) => {
                    if (minItem[1] > parseInt(item[1]) && index < maxIndex){
                        minItem = item;
                        minIndex = index;
                    }
                });
                // 最小值取最大值前至少2个点, 最大值后面的值舍弃,
                if (maxItem <= minItem) {
                    return false;
                }
                if (maxIndex > minIndex && (maxIndex - minIndex) > 0) {
                    //计算最小值和最大值的原石差值
                    let diffYuanshi = parseInt(maxItem[1]) - parseInt(minItem[1]);
                    //计算最小值和最大值的时间差
                    let maxTime = new Date(maxItem[0]);
                    let minTime = new Date(minItem[0]);
                    //结果为毫秒的差
                    let diffTime = maxTime.getTime() - minTime.getTime();
                    let diffDay = Math.floor(diffTime/(24*3600*1000));
                    //计算出每日增长预测速度
                    let speed = diffYuanshi / diffDay / 2;
                    //计算出推送90天个月后获得的原石
                    let tempData = this.myOption.series[0].data;
                    let push90Yuanshi = parseInt(speed * 140) + parseInt(tempData[tempData.length-1][1]);
                    //计算出183天后的日期
                    let finalDate = new Date(tempData[tempData.length-1][0]);
                    finalDate.setDate(finalDate.getDate() + 140);
                    let push90DateStr = `${finalDate.getFullYear()}-${(finalDate.getMonth()+1).toString().padStart(0,2)}-${(finalDate.getDate()).toString().padStart(0,2)}`;
                    this.speed = parseInt(speed * 30);
                    return [tempData[tempData.length-1], [push90DateStr, push90Yuanshi]];
                }else {
                    return false;
                }
            } else {
                // 不满足则不生成趋势线
                return false;
            }
        }
    }
})